#!/usr/bin/env python
# -*-coding:UTF-8-*-
# Author: chenzuoqing@126.com
# Create: 2018/8/28 9:48
# File  : upload_view.py

"""
文件上传视图，作为工具类存放在这
"""

import os
import time
from devops.settings import UPLOAD_DIR, UPLOAD_URI

# from rest_framework.parsers import FileUploadParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.status import HTTP_201_CREATED, HTTP_500_INTERNAL_SERVER_ERROR


class FileUploadView(APIView):
    """
    上传文件
    """
    # parser_classes = (FileUploadParser,)  # 加了会往文件内容塞一些文字，反而出错...
    permission_classes = (IsAuthenticated, )

    def put(self, request, filename, format=None):
        # filename = kwargs.get('filename')
        upload_file = request.FILES['file']
        filename = '{}_{}'.format(time.strftime('%Y%m%d%H%M%S'), filename)
        file_path = os.path.join(UPLOAD_DIR, filename)
        try:
            with open(file_path, 'wb+') as f:
                for chunk in upload_file.chunks():
                    f.write(chunk)
        except Exception as e:
            print(e)
            return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
        return Response({'state': True, 'data': '{}/{}'.format(UPLOAD_URI, filename)},
                        status=HTTP_201_CREATED)
